package com.maltys.messagingredis.redis;

import com.maltys.messagingredis.Receiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Slf4j
@Configuration
public class RedisConfiguration {
    @Autowired
    ApplicationContext applicationContext;

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 注册监听器 订阅chat 频道的消息
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    /**
     * 注册监听器
     *
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver() {
        return new Receiver();
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    public void test() throws InterruptedException {
        Receiver receiver = applicationContext.getBean(Receiver.class);
        StringRedisTemplate template = applicationContext.getBean(StringRedisTemplate.class);
        while (true) {
            if (receiver.getCount() > 0) {
                log.info("Sending message...");
                // 向channel：chat 发布消息
                template.convertAndSend("chat", "Hello from redis!");
                receiver.consume();
            }
            Thread.sleep(5000L);
        }
    }
}
